package site.xuqing.socketbus.core.handler;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.net.Socket;

import site.xuqing.nobean.NoBean;
import site.xuqing.nobean.obj.INonObject;
import site.xuqing.nobean.obj.NonObject;
import site.xuqing.socketbus.uitls.NoBeanUtil;
import site.xuqing.socketbus.uitls.NoBeanUtil.EventType;
import site.xuqing.socketbus.uitls.NoBeanUtil.Route;

/**
 * @author xuqing
 * @Description 客户端发送消息线程
 * @createTime 2022年01月21日 14:37:01
 */
public class ClientSendHandler {
    private final Socket socket;
    
    public ClientSendHandler(Socket socket) {
        this.socket = socket;
    }
    
    public void sendMsg(Route route, INonObject data) {
        INonObject event= NoBeanUtil.getBaseEvent(route, EventType.MSG);
        event.setObject("data",data);
        new Sender(event).start();
    }
    
    public void sendBind(INonObject data) {
        INonObject event= NoBeanUtil.getBaseEvent(null, EventType.BIND);
        event.setObject("data",data);
        new Sender(event).start();
    }
    
    public void sendQuit(INonObject data) {
        INonObject event= NoBeanUtil.getBaseEvent(null, EventType.QUIT);
        event.setObject("data",data);
        new Sender(event).start();
    }
    
    private class Sender extends Thread {
        private INonObject mEvent;
        public Sender(INonObject event) {
            mEvent=event;
        }
    
        @Override
        public void run() {
            try {
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
                if (mEvent != null) {
                    String json = NoBean.toJson(mEvent);
                    printWriter.println(json);
                    mEvent = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("连接异常断开");
            }
        }
    }
}
